import { useRef, useEffect } from 'react'
import flvjs from 'flv.js'

function VideoPlayer (props) {
  const player = useRef(null)
  useEffect(() => {
      const time1 = new Date().getTime()
      let playerObj = null
      if (flvjs.isSupported()) {
          let video = player.current
          if (video) {
              playerObj = flvjs.createPlayer({
              type: props.type || 'flv',
              isLive: true,
              url: props.url

              })
              playerObj.attachMediaElement(video)
              try {
                  playerObj.load()
                  playerObj.play().then(() => {
                      console.log(new Date().getTime() - time1)
                  })
              } catch (error) {
                  console.log(error)
              }
          }
      }

      return function clearPlayer() {
          if (playerObj) {
              playerObj.unload()
              playerObj.destroy()
              playerObj = null
          }
      }
  }, [props.url, props.type])
  function fullScreen() {
      if (player.current.requestFullScreen) {
          player.current.requestFullScreen()
      } else if (player.current.mozRequestFullScreen) {
          player.current.mozRequestFullScreen()
      } else if (player.current.webkitRequestFullScreen) {
          player.current.webkitRequestFullScreen()
      }
  }
  return <video muted ref={player} className={ props.className } onDoubleClick={fullScreen}></video>
}

export default VideoPlayer